<template>
  <div v-loading="loading">
    <!-- 会员操作 -->
    <el-form :model="userInfo" :inline="true" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="微信手机号:">{{ userInfo.wxMobile }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号:">{{ userInfo.mobile }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户昵称:">{{ userInfo.nickName }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="真实姓名:">{{ userInfo.realName }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="会员类型:">{{ userInfo.memberName }}</el-form-item>
        </el-col>
        <el-col v-if="userInfo.lastDate" :span="12">
          <el-form-item label="会员到期时间:">{{ userInfo.lastDate }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="开通类型:" :rules="requiredRules">
            <el-radio-group
              v-model="joinMemberType"
              @change="handleOpenMemberChange"
              :disabled="userInfo.operate == 'update'"
            >
              <el-radio v-for="(item, index) in joinTypeList" :label="item.value" :key="index">{{
                item.title
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="joinMemberType == 'GIFT'">
          <el-form-item label="赠送原因:" :rules="requiredRules">
            <el-select v-model="giftReason" placeholder="请选择">
              <el-option
                v-for="item in giftReasonsList"
                :key="item.id"
                :label="item.refDetailName"
                :value="item.refDetailName"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="销售员:" :rules="requiredRules">
            <el-select v-model="userInfo.pushCode" filterable placeholder="请搜索姓名" @change="handleChangePushCode">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.label" :value="item.pushCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-show="joinMemberType == 'FORMAL'">
          <el-form-item label="会员卡类型:" :rules="requiredRules">
            <el-radio-group v-model="userInfo.cardType" @change="handleChangeCardType">
              <el-radio v-for="(item, index) in cardTypeList" :label="item.value" :key="index">{{
                item.title
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="会员开始时间:" :rules="requiredRules">
            <el-date-picker
              v-model="userInfo.startDate"
              readonly
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy/MM/dd"
              placeholder="选择日期时间"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会员结束时间:" :rules="requiredRules">
            <el-date-picker
              v-model="userInfo.endDate"
              :readonly="joinMemberType == 'FORMAL'"
              :picker-options="pickerOptions"
              type="date"
              format="yyyy-MM-dd"
              placeholder="选择日期时间"
              value-format="timestamp"
              @focus="handleFocus"
              :default-value="userInfo.startDate"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-show="joinMemberType == 'FORMAL'">
        <el-col :span="12">
          <el-form-item label="充值金额:" :rules="requiredRules">
            <el-input
              v-model="userInfo.amount"
              type="number"
              min="0"
              placeholder="请输入金额"
              :readonly="joinMemberType == 'FORMAL'"
              clearable
              size="small"
              style="width: 240px"
              @change="handleInputChange"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="充值凭证:">
            <el-row :gutter="20">
              <el-col :span="12">
                <img v-if="userInfo.voucherUrl" :src="userInfo.voucherUrl" class="avatar" />
              </el-col>
              <el-col :span="12">
                <el-upload
                  class="upload"
                  list-type="picture-card"
                  :action="globalUploadImgUrl"
                  :show-file-list="false"
                  :data="{ filetype: '充值凭证', app: 'shulan', module: '2', sourceKey: '1' }"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleSuccess"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col class="red" :span="12" v-show="joinMemberType == 'FORMAL'">
          <el-row v-show="currentDiscounts.discountSet || currentDiscounts.activityDay">
            <el-col :span="4">充值活动：</el-col>
            <el-col :span="20">
              <div v-show="currentDiscounts.discountSet">
                {{ currentDiscounts.packageName }}{{ currentDiscounts.discountSet }}折活动，原价{{
                  currentDiscounts.oldPrice
                }}元，活动价{{ currentDiscounts.newPrice }}元
              </div>
              <div v-show="currentDiscounts.activityDay">
                {{ currentDiscounts.packageName }}赠送{{ currentDiscounts.activityDay }}天活动，赠送日期为{{
                  currentDiscounts.giftStartDate | dateFormat
                }}～{{ currentDiscounts.endDate | dateFormat }}
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
      <el-button @click="$emit('togglePop')">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {
  addMember,
  updateMemberInfo,
  getInfoByPushCode,
  getUpdateMemberEndDate,
  queryPmReferenceDetailInfoByRefCode,
} from "@/api/reviewActivities/memberManage";
import { getSaleUser, getSaleUserByName } from "@/api/reviewActivities/pushCode";
import { formatDateOnly } from "@/utils/index";
import { mapGetters } from "vuex";
import { joinTypeList } from "@/utils/config/member";

export default {
  name: "memberOption",
  props: {
    userInfo: {
      type: Object,
      default() {
        return {};
      },
    },
    showOptionPop: {
      type: Boolean,
      default: false,
    },
    joinTypeFilter: {
      type: Function,
      default() {
        return true
      }
    }
  },
  data({joinTypeFilter}) {
    return {
      requiredRules: [{ required: true, message: "" }],
      joinMemberType: "", //开通会员类型
      giftReason: "", //赠送原因
      loading: false,
      giftReasonsList: [],
      cardTypeList: [
        { value: "MONTH", title: "月卡" },
        { value: "QUARTER", title: "季卡" },
        { value: "HALFYEAR", title: "半年卡" },
        { value: "YEAR", title: "年卡" },
      ],
      joinTypeList: [...joinTypeList.filter((v) => !v.disabled).filter((v) => joinTypeFilter(v))],
      pickerOptions: {
        disabledDate: (time) => {
          if (this.userInfo.type == "1" || this.userInfo.operate == "update") {
            return time.getTime() < this.userInfo.startDate;
          } else {
            return time.getTime() < this.userInfo.startDate - 8.64e7;
          }
        },
      },
      restaurants: [], //销售员列表
      discountsList: [], // 当前充值的具体数据（结束时间 以及月卡 年卡 对应的金额）
      currentDiscounts: {}, //当前会员充值的优惠等信息
    };
  },
  watch: {
    showOptionPop: {
      handler(val) {
        if (val) {
          this.joinMemberType = this.userInfo.joinMemberType || "FORMAL";
          this.currentDiscounts = {};
          this.discountsList = [];
          this.loading = false;
          if (this.userInfo.pushCode) {
            this.handleChangePushCode(this.userInfo.pushCode);
          }
        }
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(["nickName"]),
  },
  filters: {
    dateFormat(d) {
      return formatDateOnly(new Date(d), "-");
    },
  },
  created() {
    this.loadAll();
  },
  mounted() {},
  methods: {
    // 开通类型改变
    handleOpenMemberChange(e) {
      this.userInfo.endDate = "";
      this.userInfo.cardType = "";
    },
    // 手动选择日期
    handleFocus(e) {
      // console.log("手动选择日期", e);
    },
    // 卡类型改变
    handleChangeCardType(e) {
      // console.log("卡类型改变", e);
      this.renderMemberView();
    },
    // 销售员改变
    handleChangePushCode(e) {
      let p;
      if (this.userInfo.operate == "update") {
        p = getUpdateMemberEndDate({ pushCode: e, id: this.userInfo.id })
      } else {
        p = getInfoByPushCode({ pushCode: e, agentId: this.userInfo.agentId })
      }
      p.then(({ data }) => {
        this.discountsList = data.content || [];
        this.renderMemberView();
      });
    },

    // 渲染会员信息
    renderMemberView() {
      if (this.joinMemberType !== "FORMAL") return;
      if (this.userInfo.cardType && this.discountsList.length) {
        let info = this.discountsList.find((v) => v.packageCode === this.userInfo.cardType);

        // let str = this.userInfo.operate == "update" ? "-" : "/";
        // this.userInfo.endDate = formatDateOnly(new Date(info.endDate), str);
        this.userInfo.endDate = info.endDate;
        this.userInfo.amount = info.newPrice;
        this.currentDiscounts = info;

        // console.log(info);
      }
    },

    handleInputChange(value) {
      // if (Number(value) < 0) {
      //   this.userInfo.amount = 0;
      // }
    },

    // 信息校验
    verifyErrorMessage() {
      if (!this.userInfo.pushCode) {
        return "请输入充值人";
      }

      if (this.joinMemberType == "GIFT" && !this.giftReason) {
        return "请选择赠送原因";
      }

      if (this.joinMemberType == "FORMAL") {
        if (!this.userInfo.cardType) {
          return "请选择会员卡类型";
        }
      } else {
        if (!this.userInfo.endDate) {
          return "请选择会员结束时间";
        }
      }

      return "";
    },

    async handleConfirm() {
      let msg = this.verifyErrorMessage();
      if (msg) {
        return this.$message({
          type: "error",
          message: msg,
          duration: 3000,
        });
      }

      this.loading = true;

      // 开通会员、续费会员
      if (this.userInfo.operate == "add") {
        await this.joinFetch()

        // 编辑更新会员信息
      } else if (this.userInfo.operate == "update") {
        await this.updateFetch()

      }

      this.loading = false;
    },

    async joinFetch() {
      let param = {
        source: "web",
        type: this.userInfo.type,
        voucher: this.userInfo.voucher,
        agentId: this.userInfo.agentId,
        memberCode: this.userInfo.memberCode,
        pushCode: this.userInfo.pushCode,
        joinMemberType: this.joinMemberType,
      };

      // 正式
      if (this.joinMemberType == "FORMAL") {
        param.cardType = this.userInfo.cardType;
      } else {
        param.endDate = this.userInfo.endDate;
        if (this.joinMemberType == "GIFT") {
          param.joinTypeReason = this.giftReason;
        }
      }

      const { code } = await addMember(param);
      if (code == 200) {
        this.$message({
          type: "success",
          message: this.userInfo.type == "0" ? "开通成功！" : "续约成功！",
          duration: 3000,
        });

        this.$emit("refresh");
      }
    },

    async updateFetch() {
      let param = {
        id: this.userInfo.id,
        pushCode: this.userInfo.pushCode,
      };

      if (this.userInfo.voucher) {
        param.voucher = this.userInfo.voucher
      }

      // 正式
      if (this.joinMemberType == "FORMAL") {
        param.cardType = this.userInfo.cardType;
      } else {
        param.endDate = this.userInfo.endDate;
        if (this.userInfo.endDate instanceof Date) {
          param.endDate = this.userInfo.endDate.getTime();
        }
        if (this.joinMemberType == "GIFT") {
          param.joinTypeReason = this.giftReason;
        }
      }

      const { code } = await updateMemberInfo(param);

      if (code == 200) {
        this.$message({
          type: "success",
          message: "编辑成功！",
          duration: 3000,
        });

        this.$emit("refresh");
      }
    },

    beforeAvatarUpload(file) {
      // 文件类型进行判断
      const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
      if (!isJPG) {
        this.$message.error("上传图片只能是 image/jpeg/png 格式!");
      }
      return isJPG;
    },
    //上传成功返回
    handleSuccess(res, file) {
      console.log("上传成功", res, file);
      if (file.response.length > 0) {
        this.$message({
          type: "success",
          message: "图片上传成功",
          duration: 3000,
        });
        (this.userInfo.voucher = res[0].id), (this.userInfo.voucherUrl = file.url);
      } else {
        this.$message({
          type: "error",
          message: "图片上传失败",
          duration: 3000,
        });
      }
    },

    loadAll() {
      // getSaleUser({
      getSaleUserByName({
        userName: '',
        page: 1,
        pageSize: 999
      }).then((res) => {
        let rows = res.data.content.rows;
        this.restaurants = rows
          .map((item) => {
            item.label = `${item.city ? item.city + '-' : ''} ${item.userName} - ${item.pushCode}`;
            return item;
          });
      });

      // 赠送原因
      queryPmReferenceDetailInfoByRefCode({ refCode: "membershipGiftReason" }).then(({ data }) => {
        this.giftReasonsList = data.content;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar {
  width: 148px;
  height: 148px;
  display: block;
  border-radius: 6px;
  overflow: hidden;
}
.block {
  display: block;
}

.red {
  color: #e65d6e;
}
</style>
